const express = require('express');
const router = express.Router();
// const db = require("../db");
const fn = require("../db_sql")
const moment = require("moment")
// 1.加载multer
const multer = require('multer');

// 2.设置上传文件保存到uploads文件夹中
const upload = multer({
    dest: 'uploads/'
});


//    添加：  优化写法
router.post("/add", upload.single('cover_img'), async function (req, res) {
    // 1.获取数据：曾经 req.on("data") 

    req.body.cover_img = req.file.filename
    // moment 插件获取时间的一种方式
    req.body.pub_date = moment().format("YYYY-MM-DD hh:mm:ss")
    req.body.author_id = req.user.userId

    try {
        let arr = await fn("select name from category where Id=?", req.body.cate_id)
        console.log(arr);
        req.body.cate_name = arr[0].name
        await fn(`insert into article set ?`, req.body)
        res.send({
            "status": 0,
            "message": "新增文章成功！",
        });
    } catch (error) {
        res.send({ //无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "新增文章失败！",
        });
    }

});
//    修改：/edit 
router.post("/edit", upload.single('cover_img'), async function (req, res) {

    req.body.cover_img = req.file.fieldname
    // moment 插件获取时间的一种方式
    req.body.pub_date = moment().format("YYYY-MM-DD hh:mm:ss")
    req.body.author_id = req.user.userId
    try {
        // 如果么米有更新图片 则加以下判断  如果没有提交图片的话 req.file===underfined
        let arr = await fn("select name from category where Id=?", req.body.cate_id)
        req.body.cate_name = arr[0].name
        await fn(`update article set ? where Id=?`, [req.body, req.body.Id])
        res.send({
            "status": 0,
            "message": "修改文章分类成功！",
        });
    } catch (error) {
        res.send({ // 无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "修改文章分类失败！",
        });
    }
});
//    删除：
router.get("/delete/:id", async function (req, res) {
    // 复习：post :   req.body
    //      动态接口：req.params
    //       get  :   req.query
    try {
        await fn(`delete from article where Id=?`, req.params.id)
        res.send({
            "status": 0,
            "message": "删除文章分类成功！",
        });
    } catch (error) {
        res.send({ // 无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "删除文章分类失败！",
        });
    }


});



//    列表: 分页读取全部数据
router.get("/list", async function (req, res) {
    let n = req.query.pagenum * 1;
    let m = req.query.pagesize * 1;

    let c = req.query.cate_id;
    let s = req.query.status;

    let str = "";
    if (c != undefined) {
        str += `and cate_id=${c} `
    }
    if (s != undefined) {
        str += `and state="${s}"`
    }
    let str1 = `select * from article where author_id=? ${str}  limit ?,?`
    let str2 = `select count(*) as total from article where author_id=? ${str}`
    try {
        let arr = await fn(str1, [req.user.userId, (n - 1) * m, m])
        let result = await fn(str2, req.user.userId)
        res.send({
            "status": 0,
            "message": "获取文章分类列表成功！",
            data: arr,
            total: result[0].total
        });
    } catch (error) {
        res.send({ //无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "获取文章分类列表失败！",
        });
    }

});

// 获取详情列表-->根据id查询所有数据 
router.get("/one/:id", async function (req, res) {
    // 复习：post :   req.body
    //      动态接口：req.params
    //       get  :   req.query
    try {
        let arr = await fn(`select* from article where Id=?`, req.params.id)
        res.send({
            "status": 0,
            "message": "获取文章分类成功！",
            data: arr[0]
        });
    } catch (error) {
        res.send({ // 无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "获取文章分类失败！",
        });
    }

});

// 固定4：导出模块。主app.js内部需要这个JS文件的内容！
module.exports = router;